const Koa = require('koa');
const app = new Koa();

const KoaRouter = require('koa-router');
const router = new KoaRouter();

const bodyParse = require('koa-bodyparser');
app.use(bodyParse());

const query = require('./utils/mysql');
const { passwordEncoder } = require('./utils');

const jsonwebtoken = require('jsonwebtoken');

// 使用日志中间件
const logger = require('./middleware/logger');
app.use(logger);

router.post('/zhuce', async (ctx) => {
    const { mobile, password } = ctx.request.body;
    // 非空校验
    if (!mobile || !password) {
        ctx.body = {
            code: 400,
            message: '缺少必须参数',
        };
        return;
    }
    // 手机号校验
    if (!/^1[356789]\d{9}$/.test(mobile)) {
        ctx.body = {
            code: 400,
            message: '手机号格式不正确',
        };
        return;
    }
    // 密码校验
    if (!/^[a-zA-Z0-9_]{6,20}$/.test(password)) {
        ctx.body = {
            code: 400,
            message: '密码必须是 6 ~ 20 位的字母数字下划线组合字符',
        };
        return;
    }
    // 用户手机号唯一性校验
    let res = await query('select * from user where mobile = ?', [mobile]);
    if (res.length > 0) {
        ctx.body = {
            code: 403,
            message: '该手机号已注册，不允许重复注册',
        };
        return;
    }
    // 添加用户
    res = await query('insert into user (mobile, password) values (?, ?)', [
        mobile,
        passwordEncoder(password),
    ]);
    // 判断是否插入成功
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 500,
            message: '注册失败，请稍后再试',
        };
        return;
    }
    // 注册成功
    ctx.body = {
        code: 200,
        message: '注册成功',
    };
});

router.post('/login', async (ctx) => {
    const { mobile, password } = ctx.request.body;
    // 用户是否已注册
    let res = await query('select * from user where mobile = ?', [mobile]);
    if (res.length === 0) {
        ctx.body = {
            code: 404,
            message: '该用户不存在',
        };
        return;
    }
    const user = res[0];
    // 密码是否正确
    if (user.password !== passwordEncoder(password)) {
        ctx.body = {
            code: 404,
            message: '用户密码不匹配',
        };
        return;
    }
    // 生成 token
    const token = jsonwebtoken.sign(
        {
            uid: user.id,
            mobile: user.mobile,
        },
        '123456',
        { expiresIn: '2h' },
    );

    // 返回token信息
    ctx.body = {
        code: 200,
        data: {
            token,
        },
        message: '登录成功',
    };
});

// RESTful 风格，请求方式、请求路径
router.post('/qiaodao', async (ctx) => {
    // 判断是否登录
    // const uid = ctx.headers.uid;
    // if (!uid) {
    //     ctx.body = {
    //         code: 401,
    //         message: '用户未登录，无法请求该接口',
    //     };
    //     return;
    // }
    // 获取 token
    const token = ctx.headers.token;
    if (!token) {
        ctx.body = {
            code: 401,
            message: '用户未登录，无法请求该接口',
        };
        return;
    }
    // 解析 token 的内容
    const user = jsonwebtoken.verify(token, '123456');
    const uid = user.uid;
    // 判断用户今天有没有签到
    const date = new Date();
    const Y = date.getFullYear(); // 2020
    const M = String(date.getMonth() + 1).padStart(2, '0'); // 06
    const D = String(date.getDate()).padStart(2, '0'); // 26
    const jintian = `${Y}-${M}-${D}`; // 2020-06-26
    let res = await query('SELECT * FROM signin where uid = ? and time = ?', [
        uid,
        jintian,
    ]);
    if (res.length > 0) {
        ctx.body = {
            code: 403,
            message: '用户今天已经签到了，不能重复签到',
        };
        return;
    }
    // 保存签到记录
    res = await query('insert into signin (time, uid) values (?, ?)', [
        jintian,
        uid,
    ]);
    ctx.body = {
        code: 200,
        message: '今日签到成功',
    };
});

app.use(router.routes());

app.listen(3000, () => {
    console.log('服务器已经启动了，可以访问：http://localhost:3000');
});
